package com.hejia.bulbul.controller;

import com.alibaba.fastjson.JSONObject;
import com.hejia.alauda.entity.ProductType;
import com.hejia.alauda.entity.ProductType.RedeemModel;
import com.hejia.alauda.entity.ProductTypeField;
import com.hejia.alauda.entity.Template;
import com.hejia.alauda.service.ProductService;
import com.hejia.alauda.utils.Pager;
import com.hejia.alauda.utils.PagerHelper;
import com.hejia.bulbul.entity.ProductTypeFieldModel;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;

import java.util.List;

/**
 * 产品类别管理
 * 
 *
 *
 * Created by showone on 2014 下午5:22:55.
 */
@Controller
@RequestMapping("product/type")
public class ProductTypeController extends BaseController {

	@Resource
	private ProductService productTypeService;

	@Resource
	private ProductService templateService;

    @Resource
    private ProductService productService;

    /**
     * 产品类别列表
     *
     * @param pager 分页
     * @param model model
     * @return 返回列表页面
     */
	@RequestMapping(value = "list", method = RequestMethod.GET)
	public String list(Pager<ProductType> pager, Model model) {
        pager = productTypeService.listProductType(pager);

        PagerHelper<ProductType> helper = new PagerHelper<>();
        helper.setPager(pager);
        helper.setBaseUrl("/product/type/list");

        model.addAttribute("pagerHelper", helper);
        model.addAttribute("pager", pager);
        return "/product/type/type_list";
    }

    /**
     * 添加产品类别页面
     *
     * @param model model
     * @return 产品类别添加页面
     */
	@RequestMapping(value = "add", method = RequestMethod.GET)
	public String addType(Model model) {
		List<Template> list = templateService.getAllTemplates();
		model.addAttribute("list", list);
		return "/product/type/type_input";
	}

    /**
     * 产品类别修改
     *
     * @param id 产品id
     * @param model model
     * @return 修改页面
     */
	@RequestMapping(value = "update/{id}", method = RequestMethod.GET)
	public String update(@PathVariable Long id, ModelMap model, RedirectAttributes redirectAttributes) {
        /**
         * 如果产品类别已经被使用了，那么返回产品类别的列表页面并提示产品类别已经使用，不能修改
         */
        if(productService.isTypeIdInUse(id)){
            ProductType productType = productTypeService.getProductTypeById(id);
            redirectAttributes.addFlashAttribute("productTypeInUse", productType.getName()+"：产品类别已经使用，不能修改~");
            return "redirect:/product/type/list";
        }else {
            ProductType type = productTypeService.getProductTypeById(id);
            model.addAttribute("type", type);
            if (RedeemModel.EXPIRE_KEEP.equals(type.getRedeem())) {
                JSONObject params = JSONObject.parseObject(type.getParams());
                model.addAttribute("maxRate", params.get("maxRate"));
                model.addAttribute("increaseRate", params.get("increaseRate"));
                type.setParams(params.toJSONString());
            }

            List<Template> list = templateService.getAllTemplates();
            model.addAttribute("list", list);


            List<ProductTypeField> fields = productTypeService
                    .findFieldsByTypeId(type.getId());
            model.put("fields", fields);
            return "/product/type/type_input";
        }
	}

    @RequestMapping(value = "check/{id}", method = RequestMethod.GET)
    public String check(@PathVariable Long id, ModelMap model) {
        ProductType type = productTypeService.getProductTypeById(id);
        model.addAttribute("type", type);
        if (RedeemModel.EXPIRE_KEEP.equals(type.getRedeem())) {
            JSONObject params = JSONObject.parseObject(type.getParams());
            model.addAttribute("maxRate", params.get("maxRate"));
            model.addAttribute("increaseRate", params.get("increaseRate"));
            type.setParams(params.toJSONString());
        }

        List<Template> list = templateService.getAllTemplates();
        model.addAttribute("list", list);


        List<ProductTypeField> fields = productTypeService
                .findFieldsByTypeId(type.getId());
        model.put("fields", fields);
        model.put("check", "check");
        return "/product/type/type_input";

    }


    /**
     * 产品类别添加，修改提交
     *
     * @param fieldModel 产品类别字段容器
     * @param id 产品类别
     * @param redirectAttributes redirectAttributes
     * @param type 产品类别
     * @param maxRate maxRate
     * @param increaseRate increaseRate
     * @return 返回产品类别列表
     */
	@RequestMapping(value = "update/{id}", method = RequestMethod.POST)
	public String saveType(ProductTypeFieldModel fieldModel,
			@PathVariable Long id,
			RedirectAttributes redirectAttributes, ProductType type,
			String maxRate, String increaseRate) {
		String action = "修改";
		if (type.getId() == null) {
			type = new ProductType();
			action = "添加";
		}
		if (RedeemModel.EXPIRE_KEEP.equals(type.getRedeem())) {
			JSONObject params = new JSONObject();
			params.put("maxRate", maxRate);
			params.put("increaseRate", increaseRate);
			type.setParams(params.toJSONString());
		} else {
			type.setParams(null);
		}

		if (productTypeService.updateProductType(type)) {
            productTypeService.deleteField(id);
			List<ProductTypeField> fieldList = fieldModel.getFieldList();
			// 插入Field记录
			for (int i = 0; fieldList != null && i < fieldList.size(); i++) {
				fieldList.get(i).setTypeId(type.getId());
			}
			if (fieldList != null) {
				productTypeService.insertField(fieldList);
			}
			redirectAttributes.addFlashAttribute("status", STATUS_SUCCESS);
			redirectAttributes.addFlashAttribute("msg", "产品分类" + action + "成功");
		} else {
			redirectAttributes.addFlashAttribute("status", STATUS_FAILD);
			redirectAttributes.addFlashAttribute("msg", "产品分类" + action + "失败");
		}
		return "redirect:/product/type/list";
	}
}
